﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Backend.JYD.EFDAL.DAL
{
    public class PayPlanDAL : IDAL.Bid.IPayPlan
    {
        public long AddPayPlan(Model.Bid.PayPlan plan)
        {
            using (JydDataContext db = new JydDataContext())
            {
                db.PayPlans.Add(plan);
                db.SaveChanges();
                return plan.PlanId;
            }
        }

        public bool UpdatePayPlan(Model.Bid.PayPlan plan)
        {
            using (JydDataContext db = new JydDataContext())
            {
                var query = db.PayPlans.Where(p => p.PlanId == plan.PlanId);
                var temp = query.FirstOrDefault();
                if (temp != null)
                {
                    temp = plan;
                    return db.SaveChanges() > 0;
                }
                return false;
            }
        }

        public IList<Model.Bid.PayPlan> GetPayPlanByInviteId(long inviteId)
        {
            using (JydDataContext db = new JydDataContext())
            {
                var query = db.PayPlans.Where(p => p.InviteId == inviteId);
                return query == null ? null : query.ToList();
            }
        }

        public IList<Model.Bid.PayPlan> GetRunPlan(DateTime today)
        {
            using (JydDataContext db = new JydDataContext())
            {
                //包括未到期计划，也包括逾期计划，因为有可能还款资金已经补充到位
                var query = db.PayPlans.Where(p => p.IsValid.Value && 
                        (p.PayDate.Value.CompareTo(today) <= 0));
                return query == null ? null : query.ToList();
            }
        }

        public IList<Model.Bid.PayPlan> CheckWarningPayPlan(DateTime start, int len)
        {
            using (JydDataContext db = new JydDataContext())
            {
                var query = db.PayPlans.Where(p => p.IsValid.Value && (p.PayDate.Value.CompareTo(start.AddDays(len)) <= 0));
                return query == null ? null : query.ToList();
            }
        }

        public IList<Model.Bid.PayPlan> GetLessMoneyPayPlan()
        {
            using (JydDataContext db = new JydDataContext())
            {
                var query = db.PayPlans.Where(p => p.IsValid.Value && (p.LessMoney.HasValue && p.LessMoney.Value));
                return query == null ? null : query.ToList();
            }
        }

        public IList<Model.Bid.PayPlan> GetRepayPlan(int repayDay)
        {
            using (JydDataContext db = new JydDataContext())
            {
                var query = db.PayPlans.Where(p => p.IsValid.Value && (p.WarningDay.HasValue && p.WarningDay >= repayDay));
                return query == null ? null : query.ToList();
            }
        }
    }
}
